<template>
  <div class="stuff-main">
    <el-table :data="tableList" style="width: 100%" highlight-current-row>
        <el-table-column
            label="材料名称"
            show-overflow-tooltip>
            <template slot-scope="scope">
                <p>
                    <svg-icon icon-class="ts_icon" @click="clickCheckBtn(scope.row)"/>
                    {{scope.row.name}}
                </p>
            </template>
        </el-table-column>
        <el-table-column
            label="用户上传的材料"
            show-overflow-tooltip>
            <template slot-scope="scope">
                <p v-if="scope.row.fileUrl">
                    <a :href="scope.row.fileUrl">
                        <svg-icon icon-class="download"/>
                        {{scope.row.fileName}}
                    </a>
                </p>
            </template>
        </el-table-column>
        <el-table-column
            label="材料评估"
            width="90">
            <template slot-scope="scope">
                <!-- <p>{{ getStateMate(scope.row.status) }}</p> -->
                <el-select v-model="scope.row.status" placeholder="未评估" @change="selectState" :disabled="!scope.row.fileUrl">
                    <el-option label="合格" value="1"></el-option>
                    <el-option label="不合格" value="2"></el-option>
                </el-select>
            </template>
        </el-table-column>
    </el-table>

    <SubBtn>
        <template slot="btn">
            <p class="record" @click="clickRecord">更改记录 <i class="el-icon-document"></i></p>
            <el-button round @click="clickEdit">编辑材料</el-button>
        </template>
    </SubBtn>

    <!-- 编辑材料抽屉  -->
    <el-drawer
        title="编辑材料"
        size="40%"
        :visible.sync="editDrawer"
        @close="editDrawerClose">
        <div class="edit-box">
            <h3>
                <p>删除</p>
                <p>材料名称</p>
            </h3>
            <div class="edit-list" v-for="(item, index) in tableList" :key="index">
                <i class="el-icon-remove" @click="editRemove(item)"></i>
                <el-input v-model="item.name"></el-input>
            </div>
            <!-- 添加图标 -->
            <p class="drawerAdd">
                <svg-icon icon-class="add-icon" @click="addStuff"/>
            </p>
        </div>
        <SubBtn>
            <template slot="btn">
                <div></div>
                <el-button type="primary" round @click="editSave">保存</el-button>
            </template>
        </SubBtn>
    </el-drawer>

    <!-- 材料详情抽屉 -->
    <el-drawer
        title="材料样本"
        size="40%"
        :visible.sync="drawerState"
        @close="editSampleClose">
        <div class="drawer-box">
            <!-- <el-button-group>
                <el-button type="primary" :class="selectBtnState?'isActive':''" @click="clickselectBtn">用户材料</el-button>
                <el-button type="primary" :class="selectBtnState?'':'isActive'" @click="clickselectBtn">材料样本</el-button>
            </el-button-group> -->

            <!-- 用户材料 -->
            <div class="userMaterial" v-if="selectBtnState">
                <img :src="sample.fileUrl" alt="" v-if="sample.fileUrl">
                <el-empty description="暂无数据" v-else></el-empty>
                <SubBtn>
                    <template slot="btn">
                        <el-button round>
                            <a :href="sample.fileUrl">下载</a>
                        </el-button>
                        <el-button round @click="editState('2')">不合格</el-button>
                        <el-button type="primary" round @click="editState('1')">合格</el-button>
                    </template>
                </SubBtn>
            </div>
            <!-- 材料样本 -->
            <div class="sample-box" v-else>
                <el-form ref="form" :model="sample" label-width="100px" label-position="left">
                    <el-form-item label="材料名称">
                        <el-input v-model="sample.name"></el-input>
                    </el-form-item>
                    <el-form-item label="材料要求">
                        <el-input v-model="sample.requirement" type="textarea" rows="5" resize="none"></el-input>
                    </el-form-item>
                    <el-form-item label="材料样本">
                        <!-- 点击按钮重新上传 -->
                        <el-upload
                            class="avatar-uploader"
                            action="#"
                            :on-change="getFile"
                            :auto-upload="false"
                            :file-list="fileList"
                            :show-file-list="false">
                            <el-button round>材料上传</el-button>
                        </el-upload>

                        <!-- 点击图片重新上传 -->
                        <!-- <div class="img-box" v-for="(item,index) in sampleList" :key="index">
                            <el-upload
                                :auto-upload="false"
                                class="avatar-uploader"
                                action="#"
                                :show-file-list="false"
                                :on-change="(file, fileList) => {againUpload(file, fileList, index)}">
                                <img :src="item">
                            </el-upload>
                        </div> -->

                        <!-- 文件列表 -->
                        <div class="uploadFlie-list" v-if="sample.sample">
                            <div class="flie-item" v-for="(sample,index) in sample.sample" :key="index">
                            <div>
                                <i class="el-icon-document"></i>
                                <p>{{ getMaterialName(sample) }}</p>
                            </div>
                            <div>
                                <a :href="sample" v-if="sample.includes('https://')">
                                    <svg-icon icon-class="download"/>
                                </a>
                                <i class="el-icon-delete" @click="removeFile(index)"></i>
                            </div>
                            </div>
                        </div>

                    </el-form-item>
                </el-form>
                <SubBtn>
                    <template slot="btn">
                        <div></div>
                        <div>
                            <el-button round @click="reset">重置</el-button>
                            <el-button type="primary" round @click="checkSave">保存</el-button>
                        </div>
                    </template>
                </SubBtn>
            </div>
        </div>
    </el-drawer>
  </div>
</template>

<script>
import SubBtn from "@/wss/components/subBtn.vue";
import {UrltoFile,getFileFromUrl} from "@/wss/utils/wss.js";
import { editProjectApi, uploadMaterialsSampleApi } from "@/wss/newApi_3-24/doc/project.js"
import debounce from "lodash/debounce";
export default {
    components:{SubBtn},
    props:{
        projectData: {
            type: Object,
            default: () => {
                return {};
            },
        },
    },
    data(){
        return{
            tableList: [],// 项目材料表格数据
            temTableList: [],//暂存的项目材料数据
            editBtnState: false,// 标识是否为保存按钮的状态

            editDrawer: false,//编辑材料的状态
            fileList:[],//上传的列表

            drawerState:false,//当前 材料抽屉的状态
            selectBtnState: false,// 当前选中的按钮状态 true用户材料，false材料样本
            // 样本数据
            sample:{},
            temSample:{},//暂存的数据

            sampleList:[],//展示的材料样本列表
        }
    },
    mounted(){
        this.tableList = this.projectData.materials //获取项目材料
    },
    watch:{
        //监听项目的数据是否有更新，更新的话就重新获取项目信息
        projectData(newValue,oldValue){
            this.tableList = this.projectData.materials //获取项目材料
            //获取当前材料数据
            if(this.sample.id){
                let arr = this.tableList.filter(item=>{
                    return item.id == this.sample.id
                })
                this.sample = arr[0]
            }
        },
    },
    methods:{
        // 计算当前材料是 未评估/合格/不合格
        getStateMate(state){
            if(state == "1"){
                return '合格'
            }else if(state == "2"){
                return '不合格'
            }else{
                return '未评估'
            }
        },

        // 单击切换按钮组
        clickselectBtn(){
            this.selectBtnState = !this.selectBtnState
        },

        // 点击查看按钮
        clickCheckBtn(row){
            this.sample = row //获取当前材料数据
            if(row.sample){
                this.sampleList = JSON.parse(JSON.stringify(row.sample)) //获取当前材料样本数据
            }
            this.temSample = JSON.parse(JSON.stringify(row))
            //显示项目材料查看抽屉
            this.drawerState = true
            
            this.fileList = [] //加之前先清除
            //把已上传的图片转成文件流的形式 fileRaw *****************
            if(this.sample.sample){
                this.sample.sample.forEach((item) => {
                    //获取文件名称
                    let fileName = item.substring(item.lastIndexOf("/") + 1);
                    //转成文件流
                    getFileFromUrl(item,fileName)
                    .then((response)=>{
                        let file = response
                        this.fileList.push(file);
                    })
                });
            }
            //把已上传的图片转成文件流的形式 fileRaw ***************** end
        },

        //点击重置按钮
        reset(){
            this.sample.name = JSON.parse(JSON.stringify(this.temSample.name))
            this.sample.requirement = JSON.parse(JSON.stringify(this.temSample.requirement))
            this.sampleList = JSON.parse(JSON.stringify(this.temSample.sample))
            this.fileList = []
            this.clickCheckBtn(this.temSample)
        },

        // 材料样本 点击保存按钮
        checkSave: debounce(async function(){
            await this.editProject() //项目修改接口
            await this.uploadMaterialsSample() //样本上传接口
            this.$bus.$emit('retrieveItem') // 重新获取项目的信息
            this.drawerState = false //关闭材料样本弹窗
        },1000),
        
        //点击1合格/2不合格按钮
        async editState(state){
            this.sample.status = state //修改项目材料状态
            await this.editProject() //项目修改接口
            this.$bus.$emit('retrieveItem') // 重新获取项目的信息
        },

        //修改状态的时候 1合格/2不合格
        async selectState(){
            //走修改的回调
            await this.editProject()
            await this.$bus.$emit('retrieveItem') // 重新获取项目的信息
        },

        //项目修改接口
        async editProject(){
            let data = {
                id: this.projectData.id,
                materials: this.tableList
            }
            let result = await editProjectApi(data)
            if(result.code==200){
                this.$message({ type: "success", message: "修改成功！" });
            }
        },

        //点击编辑材料按钮
        clickEdit(){
            this.editDrawer = true //显示编辑材料
            this.temTableList = JSON.parse(JSON.stringify(this.tableList)) //暂存项目材料数据
        },

        // 当关闭编辑项目材料的时候
        editDrawerClose(){
            if(!this.editBtnState){
                this.tableList = JSON.parse(JSON.stringify(this.temTableList)) //恢复项目材料数据
            }
        },

        // 关闭材料样本的时候
        editSampleClose(){
            this.fileList = []
            this.sampleList = []
            this.sample = JSON.parse(JSON.stringify(this.temSample)) //恢复项目材料样本数据
            this.clickCheckBtn(this.temSample)
            this.drawerState = false
        },
        
        //点击编辑材料的删除按钮
        editRemove(item){
            let index = this.tableList.indexOf(item);// 获得下标
            this.tableList.splice(index,1) //删除下标对应的项目材料
        },
        
        //点击添加一条项目材料样本
        addStuff(){
            this.tableList.push({
                name:'',
                requirement:'',
                status:'',
                sample:[],
            })
        },

        // 点击保存按钮
        editSave: debounce(async function(){
            // 判断如果有材料名称为空 return
            for (let i = 0; i < this.tableList.length; i++) {
                if(this.tableList[i].name==''){
                    this.$message({ type: "warning", message: "材料名称不能为空！" });
                    return
                }
            }
            // 执行保存操作，项目修改接口
            await this.editProject() //项目修改接口
            await this.$bus.$emit('retrieveItem') // 重新获取项目的信息
            this.editBtnState = true //标识改为true 当前是保存按钮
            this.editDrawer = false// 关闭编辑材料抽屉
            this.temTableList = [] //清除暂存的项目材料数据
        },1000),

        //上传文件材料样本的回调
        async getFile(file, fileList) {
            //上传判断
            const isFormat =
                file.raw.type === "image/jpeg" ||
                file.raw.type === "image/png" ||
                file.raw.type === "application/pdf" ||
                file.raw.type === "application/msword" ||
                file.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
                file.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            const isPostfix = 
                file.raw.name.split('.')[1] === "jpg" ||
                file.raw.name.split('.')[1] === "jpeg" || 
                file.raw.name.split('.')[1] === "png" || 
                file.raw.name.split('.')[1] === "pdf" ||
                file.raw.name.split('.')[1] === "doc" || 
                file.raw.name.split('.')[1] === "docx" || 
                file.raw.name.split('.')[1] === "xlsx";
            const isLt2M = file.raw.size / 1024 / 1024 < 20;

            if (!isFormat || !isPostfix) {
                this.$message.error("上传样本只能是 JPG/PNG/DOC/DOCX/PDF/XLSX 格式!");
                return;
            }else{
                if (!isLt2M) {
                    this.$message.error("上传样本大小不能超过 20MB!");
                    return;
                }else{
                    if (fileList && fileList.length > 1) {
                        fileList.shift(); 
                    }
                    this.fileList.push(file.raw);//把当前上传的文件添加到图片列表里面
                    // 显示到样本列表里面
                    this.sample.sample.push(file.name)
                    //把当前上传文件的图片转成链接放到图片展示列表里面
                    // this.sampleList.push(URL.createObjectURL(file.raw));
                }
            }
        },

        // 材料样本上传的接口
        async uploadMaterialsSample(){
            let formData = new FormData();
            formData.append("materialId", this.sample.id);
            formData.append("projectId", this.projectData.id);
            this.fileList.forEach(item=>{
                formData.append("file", item);
            })
            let result = await uploadMaterialsSampleApi(formData)
            if(result.code != 200) return
        },

        // 点击图片重新上传
        againUpload(file, fileList, index){
            // //上传判断
            const isJPGPNG =
                file.raw.type === "image/jpeg" || file.raw.type === "image/png";
            const isLt2M = file.raw.size / 1024 / 1024 < 2;
            if (!isJPGPNG) {
                this.$message.error("上传样本只能是 JPG/PNG 格式!");
                return;
            } else {
                if (!isLt2M) {
                    this.$message.error("上传样本大小不能超过 2MB!");
                    return;
                } else {
                    this.fileList[index] = file.raw
                    this.$set(this.sampleList,index,URL.createObjectURL(file.raw))
                }
            }
        },

        // 删除某一条材料
        removeFile(index){
            this.sample.sample.splice(index,1)
            this.fileList.splice(index,1)
        },

        // 获取项目材料的名称
        getMaterialName(material){
            if(material){
                let arr = material.split("/")
                let name = arr[arr.length-1]
                let id = this.sample.id
                return name.replace(id,'')
            }
        },

        // 更改记录的抽屉按钮 ***************************
        clickRecord(){
            this.$bus.$emit('openRecordDrawer')
        },
    },
}
</script>

<style scoped>
h3,h4,p,ul,li{
  margin: 0;
  padding: 0;
  list-style: none;
}

.stuff-main{
    margin-bottom: 80px;
}

.el-table .el-select{
    width: 80px;
}
.el-table .el-select >>> .el-input__inner{
    padding-left: 10px;
    padding-right: 10px;
}
.el-scrollbar .el-select-dropdown__item{
   padding-left: 10px;
}
.el-scrollbar .el-select-dropdown__item.selected,
.el-scrollbar .el-select-dropdown__item.hover{
    color: #F87A23;
}
.stuff-main >>> .el-table th.is-leaf{
    border-top: 0;
}
::v-deep .el-table .el-table__row td{
    padding: 9px 0;
}
.el-table .cell .checkBtn{
    color: #F87A23;
    cursor: pointer;
}

.el-table p>svg{
    cursor: pointer;
}

.step-main,
.step-main .el-row,
.step-main .el-col{
    height: 100%;
}
.step-main .el-card{
    position: relative;
}

/* 编辑材料的抽屉 */
.edit-box{
    padding: 0 20px;
    margin-bottom: 60px;
}
.edit-box h3{
  display: flex;
  font-size: 12px;
  font-weight: 600;
  color: #909AAA;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
}
.edit-box h3>p:first-child{
  width: 12%;
}
.edit-box h3>p:nth-child(2){
  flex: 1;
}

.edit-list{
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #EBEEF5;
}
.edit-list i{
    width: 8%;
    color: #909aaa;
    cursor: pointer;
}
.edit-list .el-input{
    flex: 1;
}
.drawerAdd{
    width: 100%;
    padding: 12px 0;
    border-bottom: 1px solid #f5f7fa;
}
.drawerAdd svg{
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #909aaa;
    margin-left: 10%;
    cursor: pointer;
}

/* 材料样本抽屉 */
.drawer-box{
    padding: 0 20px;
}

/* 按钮组 */
.el-button-group{
    width: 100%;
    margin-bottom: 20px;
}
.el-button-group .el-button{
  width: 50%;
  background-color: #F0F2F5;
  color: #2E3F5E;
  border: 1px solid #F0F2F5;
  padding: 10px 15px;
}
.el-button-group .el-button.isActive{
  background-color: #fff;
  color: #F87A23;
  font-weight: bold;
}

/* 用户材料 */
.userMaterial{
    margin-bottom: 60px;
}
.userMaterial img{
    width:100%;
}

/* 材料样本 */
.sample-box{
    margin-bottom: 60px;
}
::v-deep .sample-box .el-form-item__label{
    color: #2E3F5E;
}
::v-deep .sample-box .el-textarea__inner{
    font-family: Microsoft Yahei;
}
.sample-box img{
    width: 100%;
    margin-top: 10px;
}

/* 文件列表 */
.uploadFlie-list{
  margin-top: 15px;
  margin-bottom: 10px;
}
.uploadFlie-list p{
  margin: 0;
  padding: 0;
}
.uploadFlie-list .flie-item{
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #EFEFEF;
  line-height: 40px;
  margin-bottom: 10px;
}
.uploadFlie-list .flie-item>div{
  display: flex;
  align-items: center;
  color: #aaa;
  width: calc(100% - 50px);
}
.uploadFlie-list .flie-item>div:first-child i{
  margin-right: 10px;
}
.uploadFlie-list .flie-item>div:first-child p{
  width: calc(100% - 24px);
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
}
.uploadFlie-list .flie-item>div:last-child{
  width: 50px;
}
.uploadFlie-list .flie-item p{
  color: #666;
}
.uploadFlie-list .flie-item>div:last-child i,
.uploadFlie-list .flie-item>div:last-child svg{
  margin-left: 10px;
  cursor: pointer;
  font-size: 15px;
}
/* 文件列表 end */

/* 更改记录的样式 */
.record{
    font-size: 12px;
    cursor: pointer;
}

/* 右侧按钮样式 */
::v-deep .subBtn{
  justify-content: space-between;
  align-items: center;
  padding: 8px 30px!important;
  z-index: 99;
}
::v-deep .subBtn .el-button{
  width: 100px;
  padding: 8px 0!important;
  font-size: 14px;
  color: #606E84;
}
.subBtn .el-button >>> span,
.subBtn .el-button >>> span>a{
    display: block;
}
::v-deep .subBtn .el-button.el-button--primary{
  background-color: #F87A23;
  border-color: #F87A23;
  color: #fff;
}
</style>